<?php
require_once 'config.php';
if(!$loggedIn){
	header('Location:login.php') ;
	exit();
}
$editor = new Editor($themeId);

/**
 * The editor class that contains basic information and function for the editor to do its work.
 */
class Editor {
   public $width = 1024;
   public $height = 768;
   public $x = 110;
   public $y = 0;

   private $theme_id = -1;
   
   /**
    * Constructor.
    * It takes in the $theme_id that it is currently working on.
    */
   public function Editor($theme_id){
      $this->theme_id = $theme_id;
   }
   
   /**
    * loadIcon() generates portion of the javascript codes that loads the image of icons into the canvas.
    */
   public function loadIcon(){
      $query = "SELECT * FROM te_icon WHERE icon_theme = " . $this->theme_id;

      $result = mysql_query($query);

      while($row = mysql_fetch_array($result)){
         ?>
         canvasicon.addIcon(<?php echo $row['icon_id']; ?>,"<?php echo $row['icon_name']; ?>",<?php echo $row['icon_x']; ?>,<?php echo $row['icon_y']; ?>,<?php echo $row['icon_width']; ?>,<?php echo $row['icon_height']; ?>,"<?php echo $row['icon_image']; ?>");
<?php }

   }
   
   public function getBgPath(){
	   global $themeRow;
	  return "bg/".$themeRow['desktop_bg'];
   }
	   
   
   /**
    * loadDataURL() extracts the image dataurl of the theme.
    */
   public function loadDataURL(){

      $query = "SELECT theme_image FROM te_theme WHERE theme_id = " . $this->theme_id;
      $result = mysql_query($query);

      $row = mysql_fetch_array($result);
      echo $row['theme_image'];
      
   }
   
   /**
    * loadIconMovement() extracts the iconmovement for the theme.
    */
   public function loadIconMovement(){
      $query = "SELECT theme_iconmovement FROM te_theme WHERE theme_id = " . $this->theme_id;
      $result = mysql_query($query);

      $row = mysql_fetch_array($result);
      echo $row['theme_iconmovement'];
      
   }

   /**
    * save() saves the dataurl and the icons information. Icons are passed in as array serialised by the javascript file.
    */
   public function save($dataurl,$icons,$iconmovement){

      mysql_query("UPDATE te_theme SET theme_image='$dataurl' WHERE theme_id=" . $this->theme_id);

      foreach($icons as $icon){
         mysql_query("UPDATE te_icon SET icon_x=".$icon['x'].", icon_y=".$icon['y'].", icon_width=".$icon['width'].", icon_height=".$icon['height'].", icon_name='".$icon['name']."', icon_image='".$icon['src']."' WHERE icon_id=".$icon['id']." AND icon_theme=".$this->theme_id);
      }

      mysql_query("UPDATE te_theme SET theme_iconmovement='$iconmovement' WHERE theme_id=" . $this->theme_id);

      echo "Saved";
   }
   
   
   public function loadDropbox(){

      $query = "SELECT icon_id,dropboxitem_id,dropboxitem_icon,dropboxitem_name,dropboxitem_link FROM te_dropboxitem,te_icon WHERE icon_id = dropboxitem_icon AND icon_theme = " . $this->theme_id . " ORDER BY dropboxitem_icon,dropboxitem_id";
      
      $result = mysql_query($query);


      $curr_item = -1;
      $dropboxlink = "";
      echo "         var dropboxes = new Array();\n";
      $dropboxlink = "         var dropboxlinks = new Array();\n";
      while($row = mysql_fetch_array($result)){
         if($row['dropboxitem_icon']==$curr_item){
            echo ",'".$row['dropboxitem_name']."'";
            $dropboxlink .= ",'".$row['dropboxitem_link']."'";
         }else{
            if($curr_item!=-1){
               echo "); \n";
               $dropboxlink .= ");\n";
            }
            $curr_item = $row['dropboxitem_icon'];
            echo "dropboxes[".$row['icon_id']."] = new Array('".$row['dropboxitem_name']."'";
            $dropboxlink .= "dropboxlinks[".$row['icon_id']."] =  new Array('".$row['dropboxitem_link']."'";
         }
      }
      if(mysql_num_rows($result)>0){
	      echo ");\n";
	      $dropboxlink .= ");\n";
      }
      echo $dropboxlink;
   }
}

if(isset($_POST['image']) && isset($_POST['icons']) && isset($_POST['iconmovement'])){
   $iconstring = str_replace("\\","",$_POST['icons']);
   $icons = unserialize($iconstring);

   $editor->save($_POST['image'],$icons,$_POST['iconmovement']);
}else{

?><html>
   <head>
      <title>Online Workspace</title>
<script type="text/javascript">
	var djConfig = {
		parseOnLoad: true
	};
</script>
<script src="dojo/dojo/dojo.js"></script>
      <script type="text/javascript">
	  
dojo.require("dijit.Dialog");
dojo.require("dijit.TitlePane");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.dnd.Moveable");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojox.data.JsonRestStore");
dojo.require("dojox.grid.DataGrid");

const CANVAS = {BG:"canvasBg",DRAW:"canvasDraw",ICON:"canvasIcon",TOOL:"canvasTool",SAVE:"canvasSave"};
const DIMENSION = {X:<?php echo $editor->x;?>,Y:<?php echo $editor->y;?>,WIDTH:<?php echo $editor->width;?>,HEIGHT:<?php echo $editor->height;?>};
const TOOL = {ERASER:0,PENCIL:1,BRUSH:2,ICONDRAG:3};

var mouse={x:0,y:0,m:0,n:0};
var pen={type:TOOL.PENCIL,color:"#000",width:0};
var current={canvas:CANVAS.DRAW,mousedown:false,iconmovement:"<?php $editor->loadIconMovement(); ?>"};
var icons = new Array();
 
<?php $editor->loadDropbox();?>
 
 document.onmousemove = mouseMove;
 document.onmousedown = mouseDown;
 document.onmouseup = mouseUp;

 window.onload = function(){
	var canvases = document.getElementsByTagName('canvas');
	for (i in canvases) {
	   disableSelection(canvases[i]);
	}
	var images = document.getElementsByTagName('img');
	for (i in images) {
	   disableSelection(images[i]);
	}
	//##########- ADD ICON HERE (START) -##########//
	//canvasicon.addIcon(id,name,x,y,width,height,src);
	<?php $editor->loadIcon(); ?>
	//##########- ADD ICON HERE  (END)  -##########//
	
	refreshAll();
	action('drag');
 };
 
 // update the window size
 function refreshAll(){
	document.getElementById("canvasBg").width = DIMENSION.WIDTH;
	document.getElementById("canvasDraw").width = DIMENSION.WIDTH;
	document.getElementById("canvasIcon").width = DIMENSION.WIDTH;
	document.getElementById("canvasTool").width = DIMENSION.WIDTH;
	document.getElementById("canvasSave").width = DIMENSION.WIDTH;
	document.getElementById("topbar").style.width = DIMENSION.WIDTH;
	
	document.getElementById("canvasBg").height = DIMENSION.HEIGHT;
	document.getElementById("canvasDraw").height = DIMENSION.HEIGHT;
	document.getElementById("canvasIcon").height = DIMENSION.HEIGHT;
	document.getElementById("canvasTool").height = DIMENSION.HEIGHT;
	document.getElementById("canvasSave").height = DIMENSION.HEIGHT;
	
	var canvases = document.getElementsByTagName('canvas');
	for (i in canvases) {
	   disableSelection(canvases[i]);
	}
	var images = document.getElementsByTagName('img');
	for (i in images) {
	   disableSelection(images[i]);
	}
	
	canvasBg.loadImageAsBackgroud('<?php echo $editor->getBgPath(); ?>');
	canvasicon.refresh();
	canvasdraw.load("<?php $editor->loadDataURL(); ?>");
 }
	 
 
 /**
  * action(command) method sets the pen that is being selected.
  */
 function action(command){
	if(command=="eraser"){
	   current.canvas=CANVAS.DRAW;
	   pen.type=TOOL.ERASER;
	   pen.width=5;
	}else if(command=="pencil"){
		openColorPane();
	   current.canvas=CANVAS.DRAW;
	   pen.type=TOOL.PENCIL;
	   pen.width=1;
	}else if(command=="brush"){
		openColorPane();
	   current.canvas=CANVAS.DRAW;
	   pen.type=TOOL.BRUSH;
	   pen.width=5;
	}else if(command=="drag"){
		closeColorPane();
	   current.canvas=CANVAS.ICON;
	   pen.type=TOOL.ICONDRAG;
	   pen.width=5;
	}else if(command=="clear"){
	   canvasdraw.clear();
	}else if(command=="save"){
	   save();
	}else if(command=="null"){
	}
 }
 
 /**
  * Changes the color of the pen
  */
 function cColor(color){
	pen.color=color;
 }
 
 /**
  * This method is called everytime a mouse is clicked
  */
 function mouseDown(e){
	mouse.m = mouse.x;
	mouse.n = mouse.y;
	if(isInCanvas())
	   current.mousedown=true;
	current.selectedicon=canvasicon.selectIcon();
	canvasicon.updateOffset();
	compute();
 }
 
 /**
  * Returns true if cursor is within boundary of canvas
  */
 function isInCanvas(){
	if(mouse.x<0) return false;
	if(mouse.y<0) return false;
	if(mouse.x>DIMENSION.WIDTH) return false;
	if(mouse.y>DIMENSION.HEIGHT) return false;
	return true;
 }
 
 /**
  * This method is called everytime a mouse click is released
  */
 function mouseUp(e){
	current.mousedown=false;
 }
 
 /**
  * This method is called everytime the mouse moves.
  */
 function mouseMove(e){
	mouse.m = mouse.x;
	mouse.n = mouse.y;
	mouse.x = e.pageX-DIMENSION.X;
	mouse.y = e.pageY-DIMENSION.Y;
	compute();
 }
 
 /**
  * computes the thing it needs to do based on the action set.
  */
 function compute(){
	canvastool.refresh();
	if(!current.mousedown)return;
	switch(pen.type){
	   case TOOL.PENCIL:
	   case TOOL.BRUSH:
		  canvasdraw.line(mouse.m,mouse.n,mouse.x,mouse.y,pen.width,pen.color);
		  break;
	   case TOOL.ERASER:
		  canvasdraw.erase(mouse.x,mouse.y,pen.width)
		  break;
	   case TOOL.ICONDRAG:
		  canvasicon.moveIcon();
	}
 }
 

 /**
  * *************************************************************************************
  * Object Literal (canvasdraw) stores necessary function related with the drawing canvas
  * *************************************************************************************
  */
 var canvasdraw = {
	//Draws a line from m,n to x,y
	line:function(m,n,x,y,width,color){
	   var c = document.getElementById(CANVAS.DRAW).getContext("2d");
	   c.beginPath();
	   c.strokeStyle = color;
	   c.lineWidth   = width*2;
	   c.moveTo(m,n);
	   c.lineTo(x,y);
	   c.stroke();
	   c.fillStyle=color;
	   c.arc(m,n,width,0,Math.PI*2,true);
	   c.arc(x,y,width,0,Math.PI*2,true);
	   c.fill();
	   c.closePath();
	},
	//Erase a square around x,y specified by width
	erase:function(x,y,width){
	   var c = document.getElementById(CANVAS.DRAW).getContext("2d");
	   c.beginPath();
	   c.clearRect(x-width,y-width,width*2,width*2);
	   c.fill();
	   c.closePath();
	},
	//Clears entire canvas
	clear:function(){
	   var c = document.getElementById(CANVAS.DRAW).getContext("2d");
	   c.beginPath();
	   c.clearRect(0,0,DIMENSION.WIDTH,DIMENSION.HEIGHT);
	   c.fill();
	   c.closePath();
	},
	//Loads the canvas with an image specified by the dataurl
	load:function(dataurl){
	   var c = document.getElementById(CANVAS.DRAW).getContext("2d");
	   var img = new Image();
	   img.onload = function(){
		  c.width = DIMENSION.WIDTH;
		  c.height = DIMENSION.HEIGHT;
		  c.drawImage(img,0,0);
	   };
	   img.src = dataurl;
	},
	//Extracts the current dataurl representation of the image drawn on canvas
	dataurl:function(){
	   var c=document.getElementById(CANVAS.DRAW);
	   return c.toDataURL("image/png");
	}
 }

 
 /**
  * **********************************************************************************
  * Object Literal (canvasBg)
  * **********************************************************************************
  */
 var canvasBg = {
	//Loads the canvas with an external image
	loadImageAsBackgroud:function(imagePath){
	   var c = document.getElementById(CANVAS.BG).getContext("2d");
	   var img = new Image();
	   img.onload = function(){
		  c.width = DIMENSION.WIDTH;
		  c.height = DIMENSION.HEIGHT;
		  c.drawImage(img,0,0);
	   };
	   img.src = imagePath;
	}
 }
 
  
	var iconId = new Array();
	var iconCount = 0;
 /**
  * **********************************************************************************
  * Object Literal (canvasicon) stores necessary function related with the icon canvas
  * **********************************************************************************
  */
 var canvasicon = {
	//Refresh the current state of icon canvas. i.e:clears and redraws the icon canvas
	refresh:function(){
	   var c = document.getElementById(CANVAS.ICON).getContext("2d");
	   c.clearRect(0,0,DIMENSION.WIDTH,DIMENSION.HEIGHT);
	   for (i in icons){
			 canvasicon.drawIcon(icons[i]);
	   }
	},
	
	// draw the context menu for an desktop item
	drawMenu: function(){
		//get the context menu div
		var context_menu = document.getElementById("context_menu");
		context_menu.innerHTML = "";
		// set the position of context menu. Make sure it's inside the desktop screen
		if(mouse.x > DIMENSION.WIDTH - 210){
			context_menu.style.left = DIMENSION.WIDTH + <?php echo $editor->x; ?> - 210;
		}else{
			context_menu.style.left = mouse.x + <?php echo $editor->x; ?>;
		}
		
		context_menu.style.top = mouse.y + <?php echo $editor->y; ?>;
		
		
		if(canvasicon.selected != -1){
			canvasicon.lastSelected = canvasicon.selected;
			// add items to the context menu
			var names = dropboxes[icons[canvasicon.selected].id];
			var links = dropboxlinks[icons[canvasicon.selected].id];
			if(names != undefined){
				for(var i=0; i<names.length; i++){
					var menuItem = document.createElement("div");
					menuItem.innerHTML = "<a href='"+links[i]+"'>"+names[i]+"</a>";
					menuItem.setAttribute("class", "context_menu_item");
					context_menu.appendChild(menuItem);
				}
			}else{
				// a folder
				// menu item: open folder
				var openFolderMenuItem = document.createElement("div");
				openFolderMenuItem.innerHTML = "<a href='javascript:openFolder(123);'>Open</a>";
				openFolderMenuItem.setAttribute("class", "context_menu_item");
				context_menu.appendChild(openFolderMenuItem);
				// menu item: rename folder
				var renameFolderMenuItem = document.createElement("div");
				renameFolderMenuItem.innerHTML = "<a href='#'>Rename</a>";
				renameFolderMenuItem.setAttribute("class", "context_menu_item");
				context_menu.appendChild(renameFolderMenuItem);
				// menu item: delete folder
				var deleteFolderMenuItem = document.createElement("div");
				deleteFolderMenuItem.innerHTML = "<a href='javascript:deleteFolder()'>Delete</a>";
				deleteFolderMenuItem.setAttribute("class", "context_menu_item");
				context_menu.appendChild(deleteFolderMenuItem);
			}
		}else{
			// display the main desktop context menu
			// menu item: create new folder
			var newFolderMenuItem = document.createElement("div");
			newFolderMenuItem.innerHTML = "<a href='javascript:createNewFolderForm()'>Create New Folder</a>";
			newFolderMenuItem.setAttribute("class", "context_menu_item");
			context_menu.appendChild(newFolderMenuItem);
			
			// menu item: Auto arrange
			var arrangeMenuItem = document.createElement("div");
			arrangeMenuItem.innerHTML = "<a href='javascript:autoArrageForm()'>Auto Arrange Icons</a>";
			arrangeMenuItem.setAttribute("class", "context_menu_item");
			context_menu.appendChild(arrangeMenuItem);
			
			// menu item: Change Desktop Background
			var changeBgMenuItem = document.createElement("div");
			changeBgMenuItem.innerHTML = "<a href='javascript:changeBackgroundForm()'>Change Desktop Background</a>";
			changeBgMenuItem.setAttribute("class", "context_menu_item");
			context_menu.appendChild(changeBgMenuItem);
		}
		// display the context menu
		context_menu.style.display = "block";
	},
	
	// remove the context menu
	clearMenu: function(){
		var context_menu = document.getElementById("context_menu");
		context_menu.style.display = "none";
	},
		
	
	//Draws the individual icon on the canvas. see the refresh function.
	drawIcon:function(icon){
	   var c = document.getElementById(CANVAS.ICON).getContext("2d");
	   var img = new Image();
	   img.onload = function(){
			c.drawImage(img,icon.x,icon.y,icon.width,icon.height);
		}
	   img.src = icon.src;
	},
	//Adds a new icon into the icons array.
	addIcon:function(id,name,x,y,width,height,src){
	   icon = {id:id,name:name,x:x,y:y,width:width,height:height,src:src};
	   icons.push(icon);
	},
	//Returns the icons' array index that the cursor is hovering over.
	hoverIcon:function(){
	   var list = new Array();
	   for (i in icons){
		  if(mouse.x-icons[i].x<icons[i].width
		  && mouse.x-icons[i].x>0
		  && mouse.y-icons[i].y<icons[i].height
		  && mouse.y-icons[i].y>0){
			 list.push(i);
		  }
	   }
	   var tmp = list.pop();
	   if(tmp>=0){
		  return tmp;
	   }else{
		  return -1;
	   }
	},
	//Sets the selected icon as the one that the cursor is hovering over. See hoverIcon function.
	selectIcon:function(){
	   canvasicon.selected = canvasicon.hoverIcon();
	},
	//Updates the new position of the icons and redraws the icon canvas. See refresh function.
	updateIcon:function(iconIndex){
		if(icons[iconIndex] != null){
		   icons[iconIndex].x=mouse.x-icons[iconIndex].offsetX;
		   icons[iconIndex].y=mouse.y-icons[iconIndex].offsetY;
		   canvasicon.refresh();
		}
	},
	//Moves the icon to new position. See selected function.
	moveIcon:function(){
	   canvasicon.updateIcon(canvasicon.selected);
	},
	//Updates the offset of the cursor and it's selected icon
	updateOffset:function(){
	   try{
		  if(canvasicon.selected>=0){
			 icons[canvasicon.selected].offsetX=mouse.x-icons[canvasicon.selected].x;
			 icons[canvasicon.selected].offsetY=mouse.y-icons[canvasicon.selected].y;
		  }
	   }catch(ex){
	   }
	},
	//Variable to track the currently selected icon.
	selected:-1
	
 };
 
 /**
  * **********************************************************************************
  * Object Literal (canvastool) stores necessary function related with the tool canvas
  * **********************************************************************************
  */
 var canvastool = {
	//refresh the location of the tools.
	refresh:function(){
	   var c = document.getElementById(CANVAS.TOOL).getContext("2d");
	   c.clearRect(0,0,DIMENSION.WIDTH,DIMENSION.HEIGHT);
	   switch(pen.type){
		  case TOOL.PENCIL:
		  case TOOL.BRUSH:
			 c.beginPath();
			 c.fillStyle=pen.color;
			 c.arc(mouse.x,mouse.y,pen.width,0,Math.PI*2,true);
			 c.fill();
			 c.closePath();
			 break;
		  case TOOL.ERASER:
			 c.beginPath();
			 c.fillStyle="#FFF";
			 c.fillRect(mouse.x-pen.width,mouse.y-pen.width,pen.width*2,pen.width*2);
			 c.fill();
			 c.strokeStyle = "#000";
			 c.lineWidth   = 1;
			 c.moveTo(mouse.x-pen.width,mouse.y-pen.width);
			 c.lineTo(mouse.x-pen.width,mouse.y+pen.width);
			 c.lineTo(mouse.x+pen.width,mouse.y+pen.width);
			 c.lineTo(mouse.x+pen.width,mouse.y-pen.width);
			 c.lineTo(mouse.x-pen.width,mouse.y-pen.width);
			 c.stroke();
			 c.closePath();
			 break;
		  case TOOL.ICONDRAG:
			 var w=2;
			 c.beginPath();
			 c.strokeStyle = "#000";
			 c.lineWidth   = w;
			 c.moveTo(mouse.x-pen.width,mouse.y);
			 c.lineTo(mouse.x+pen.width,mouse.y);
			 c.moveTo(mouse.x,mouse.y-pen.width);
			 c.lineTo(mouse.x,mouse.y+pen.width);
			 c.stroke();
			 c.closePath();
			 break;
			 
	   }
	   canvastool.highlightIcon();
	},
	//If in ICON Drag mode, highlights the icon.
	highlightIcon:function(){
	   if(pen.type!=TOOL.ICONDRAG)return;
	   
	   var selected = -1;
	   if(current.mousedown){
		  selected = canvasicon.selected;
	   }else{
		  selected = canvasicon.hoverIcon();
	   }

	   if(selected<0)return;
	   var c = document.getElementById(CANVAS.TOOL).getContext("2d");
	   c.beginPath();
	   c.strokeStyle = "#0FF";
	   c.lineWidth   = 2;
	   c.moveTo(icons[selected].x,icons[selected].y);
	   c.lineTo(icons[selected].x+icons[selected].width,icons[selected].y);
	   c.lineTo(icons[selected].x+icons[selected].width,icons[selected].y+icons[selected].height);
	   c.lineTo(icons[selected].x,icons[selected].y+icons[selected].height);
	   c.lineTo(icons[selected].x,icons[selected].y);
	   c.stroke();

	   c.fillStyle = "#0FF";
	   c.fillRect( icons[selected].x , icons[selected].y + icons[selected].height - 10, icons[selected].width , 10);
	   
	   c.fillStyle = "#000";
	   c.fillText(icons[selected].name, icons[selected].x , icons[selected].y + icons[selected].height - 1 , icons[selected].width );
	   c.closePath();
	   
	}
 };
 
 /**
  * save() function calls a script on the server and sends information to the server to be saved.
  */
 function save(){
	if (window.XMLHttpRequest)// code for IE7+, Firefox, Chrome, Opera, Safari
	   xmlhttp=new XMLHttpRequest();
	else// code for IE6, IE5
	   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

	xmlhttp.onreadystatechange=function(){
								  if (xmlhttp.readyState==4 && xmlhttp.status==200){
									 alert(xmlhttp.responseText);
								  }
							   };
	xmlhttp.open("POST","<?php echo $_SERVER['PHP_SELF'];?>",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("image="+encodeURIComponent(canvasdraw.dataurl())+"&icons="+serialize(icons)+"&iconmovement="+encodeURIComponent(current.iconmovement));
 }
 
 function changeIconMovement(element){
	current.iconmovement = element.value;
 }
 
 /**
  * disableSelection prevents canvas element from being highlighted easily.
  */
 function disableSelection(element) {
	if (typeof element.onselectstart != 'undefined') {
	   element.onselectstart = function() { return false; };
	}/* else if (typeof element.style.MozUserSelect != 'undefined') {
	   element.style.MozUserSelect = 'none';
	}*/ else {
	   element.onmousedown = function() { return false; };
	}
 }

 /**
  * Serialise a Javascript Array into PHP Serialised Array.
  * Used when passing the icons array into the php script.
  *
  *  Returns a string representation of variable (which can later be unserialized)  
  *  
  *  version: 1006.1915
  *  discuss at: http://phpjs.org/functions/serialize
  *  +   original by: Arpad Ray (mailto:arpad@php.net)
  *  +   improved by: Dino
  *  +   bugfixed by: Andrej Pavlovic
  *  +   bugfixed by: Garagoth
  *  +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
  *  +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
  *  +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
  *  +      input by: Martin (http://www.erlenwiese.de/)
  *  +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  *  -    depends on: utf8_encode
  *  %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
  *  %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
  *  *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
  *  *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
  *  *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
  *  *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
  */
 function serialize (mixed_value) {
	 var _getType = function (inp) {
		 var type = typeof inp, match;
		 var key;
		 if (type == 'object' && !inp) {
			 return 'null';
		 }
		 if (type == "object") {
			 if (!inp.constructor) {
				 return 'object';
			 }
			 var cons = inp.constructor.toString();
			 match = cons.match(/(\w+)\(/);
			 if (match) {
				 cons = match[1].toLowerCase();
			 }
			 var types = ["boolean", "number", "string", "array"];
			 for (key in types) {
				 if (cons == types[key]) {
					 type = types[key];
					 break;
				 }
			 }
		 }
		 return type;
	 };
	 var type = _getType(mixed_value);
	 var val, ktype = '';
	 
	 switch (type) {
		 case "function": 
			 val = ""; 
			 break;
		 case "boolean":
			 val = "b:" + (mixed_value ? "1" : "0");
			 break;
		 case "number":
			 val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
			 break;
		 case "string":
			 mixed_value = this.utf8_encode(mixed_value);
			 val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
			 break;
		 case "array":
		 case "object":
			 val = "a";
			 var count = 0;
			 var vals = "";
			 var okey;
			 var key;
			 for (key in mixed_value) {
				 ktype = _getType(mixed_value[key]);
				 if (ktype == "function") { 
					 continue; 
				 }
				 
				 okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
				 vals += this.serialize(okey) +
						 this.serialize(mixed_value[key]);
				 count++;
			 }
			 val += ":" + count + ":{" + vals + "}";
			 break;
		 case "undefined": // Fall-through
		 default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
			 val = "N";
			 break;
	 }
	 if (type != "object" && type != "array") {
		 val += ";";
	 }
	 return val;
 }

 /**
  * Needed to be used by the serialize function.
  * 
  *  Encodes an ISO-8859-1 string to UTF-8  
  *  
  *  version: 1006.1915
  *  discuss at: http://phpjs.org/functions/utf8_encode
  *  +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
  *  +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  *  +   improved by: sowberry
  *  +    tweaked by: Jack
  *  +   bugfixed by: Onno Marsman
  *  +   improved by: Yves Sucaet
  *  +   bugfixed by: Onno Marsman
  *  +   bugfixed by: Ulrich
  *  *     example 1: utf8_encode('Kevin van Zonneveld');
  *  *     returns 1: 'Kevin van Zonneveld'
  */
 function utf8_encode ( argString ) {
	 var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  
	 var utftext = "";
	 var start, end;
	 var stringl = 0;
  
	 start = end = 0;
	 stringl = string.length;
	 for (var n = 0; n < stringl; n++) {
		 var c1 = string.charCodeAt(n);
		 var enc = null;
  
		 if (c1 < 128) {
			 end++;
		 } else if (c1 > 127 && c1 < 2048) {
			 enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
		 } else {
			 enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
		 }
		 if (enc !== null) {
			 if (end > start) {
				 utftext += string.substring(start, end);
			 }
			 utftext += enc;
			 start = end = n+1;
		 }
	 }
  
	 if (end > start) {
		 utftext += string.substring(start, string.length);
	 }
  
	 return utftext;
 }
 
 function dump(text){
	document.status.display.value=text;
 }
 
 var lastX;
 var lastY;
 // show the create folder form
function createNewFolderForm(){
	lastX = mouse.x;
	lastY = mouse.y;
	canvasicon.clearMenu();
	createFolderDlg.show();
}

// arrange icons
function doArrangeIcons(){
	var style = getArrangeIconValue();
	if(style == "vertical"){
		// arrange icons vertically
		var currentLeft = 30;
		var currentTop = 60;
		for(var i=0; i<icons.length; i++){
			icons[i].x = currentLeft;
			icons[i].y = currentTop;
			currentTop += 90;
			if(currentTop > DIMENSION.HEIGHT -70){
				currentTop = 60;
				currentLeft += 90;
			}
		}
		canvasicon.refresh();
	}else if(style == "horizontal"){
		// arrange icons horizontally
		var currentLeft = 30;
		var currentTop = 60;
		for(var i=0; i<icons.length; i++){
			icons[i].x = currentLeft;
			icons[i].y = currentTop;
			currentLeft += 90;
			if(currentLeft > DIMENSION.WIDTH -70){
				currentLeft = 30;
				currentTop += 90;
			}
		}
		canvasicon.refresh();
	}else if(style == "circle"){
		// arrange icons in a circle
		var distance = 90;
		var circumference = icons.length*distance;
		var radius = circumference/(2*Math.PI);
		var currentAngle = 0;
		var centerX = DIMENSION.WIDTH/2 - 30;
		var centerY = DIMENSION.HEIGHT/2 - 30;
		for(var i=0; i<icons.length; i++){
			icons[i].x = centerX + Math.sin(currentAngle)*radius;
			icons[i].y = centerY + Math.cos(currentAngle)*radius;
			currentAngle += 2*Math.PI/icons.length;
		}
		canvasicon.refresh();
	}
}

// create a new folder
function doCreateFolder(){
	var folderName = document.getElementById("foldername").value;
	// ajax call to server to create a folder
	var folderIconPath = "image/folder_"+getFolderIconValue()+".png";
	dojo.xhrPost({
		url:"ajax_create_folder.php",
		content: {
			"image": folderIconPath,
			"icon_x": lastX,
			"icon_y": lastY,
			"icon_name": folderName
		},
		handleAs:"text",
		load: function(data){
			createFolderDlg.hide();
			// update the local list of folders
			var folderId = data;
			canvasicon.addIcon(folderId,folderName,lastX,lastY,64,64,folderIconPath);
			canvasicon.refresh();
		}
	});
}

// change background
function doChangeBackground(){
	dojo.xhrPost({
		url:"ajax_change_background.php",
		content: {
			"image": getBgImage()
		},
		handleAs:"text",
		load: function(data){
			canvasBg.loadImageAsBackgroud('bg/'+getBgImage());
		}
	});
}

function deleteFolder(){
	canvasicon.clearMenu();
	if(confirm("Do you want to delete this folder?")){
		console.log('deleting '+icons[canvasicon.lastSelected].id);
		dojo.xhrPost({
			url:"ajax_delete_folder.php",
			content: {
				"folderId": icons[canvasicon.lastSelected].id
			},
			handleAs:"text",
			load: function(data){
				icons.splice(canvasicon.lastSelected,1);
				canvasicon.refresh();
			}
		});
	}
}


function windowWidth(){
	if (parseInt(navigator.appVersion)>3) {
	 if (navigator.appName=="Netscape") {
	  return window.innerWidth-16;
	 }
	 if (navigator.appName.indexOf("Microsoft")!=-1) {
	  return document.body.offsetWidth-20;
	 }
	}
}

function getArrangeIconValue()
{
for (var i=0; i < document.arrangeIconForm.arrangeIcons.length; i++)
   {
   if (document.arrangeIconForm.arrangeIcons[i].checked)
      {
       return document.arrangeIconForm.arrangeIcons[i].value;
      }
   }
}

function getFolderIconValue()
{
for (var i=0; i < document.folderIconForm.folderIcon.length; i++)
   {
   if (document.folderIconForm.folderIcon[i].checked)
      {
       return document.folderIconForm.folderIcon[i].value;
      }
   }
}

function getBgImage(){
for (var i=0; i < document.backgroundForm.backgroundImage.length; i++)
   {
   if (document.backgroundForm.backgroundImage[i].checked)
      {
       return document.backgroundForm.backgroundImage[i].value;
      }
   }
}

function getTime() {
   var dTime = new Date();
  var hours = dTime.getHours();
   var minute = dTime.getMinutes();
   var second = dTime.getSeconds();
   var period = "AM";
   if (hours > 12) {
       period = "PM"
   }
    else {
        period = "AM";
    }
    hours = ((hours > 12) ? hours - 12 : hours)
   return hours + ":" + minute + ":"+second+ " " + period
}

function updateTime(){
	document.getElementById("topbarright").innerHTML = getTime();
	setTimeout("updateTime()",1000);
}


function windowHeight(){
	if (parseInt(navigator.appVersion)>3) {
	 if (navigator.appName=="Netscape") {
	  return window.innerHeight-16;
	 }
	 if (navigator.appName.indexOf("Microsoft")!=-1) {
	  return document.body.offsetHeight-20;
	 }
	}
}

function resizeWindow(){
	DIMENSION.WIDTH = windowWidth() - 100;
	DIMENSION.HEIGHT = windowHeight()+20;
	refreshAll();
}

function makeMoveable(node) {
	var obj = dojo.byId(node);
	obj.style.top = windowHeight() - 70;
	obj.style.left = windowWidth() - 700;
	var dnd = new dojo.dnd.Moveable(obj);
}

function closeColorPane(){
	document.getElementById("colorPane").style.display = "none";
}

function openColorPane(){
	document.getElementById("colorPane").style.display = "block";
}

function openFolder(folderId){
	canvasicon.clearMenu();
	folderContentDlg.show();
}

function autoArrageForm(){
	canvasicon.clearMenu();
	autoArrangeDlg.show();
}

function changeBackgroundForm(){
	canvasicon.clearMenu();
	desktopBackgroundDlg.show();
}
		
dojo.addOnLoad(function() {
	resizeWindow();
	updateTime();
	dojo.connect(createFolderBtn, "onClick", "doCreateFolder");
	dojo.connect(arangeIconsBtn, "onClick", "doArrangeIcons");
	dojo.connect(changeBackgroundBtn, "onClick", "doChangeBackground");
	makeMoveable('colorPane');
	
	// sample data for folder content
	var jsonStore = new dojo.data.ItemFileReadStore({ url: "foldercontent.php" });
	var layout = [
			{
					cells: [[
							{ field: "name", name: "File Name", width: 'auto'},
							{ field: "size", name: "Size", width: '70px'},
							{ field: "date", name: "Last Update", width: '100px'}
					]]
			}
	];
	var grid = new dojox.grid.DataGrid({
			id: "grid",
			query: { id: "*" },
			store: jsonStore,
			structure: layout
	}, "gridNode");
	grid.startup();
});

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v9.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
      </script>
      <link href="css/main.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="dojo/dijit/themes/tundra/tundra.css" />
    <link rel="stylesheet" type="text/css" href="dojo/dojox/grid/resources/Grid.css" />
    <link rel="stylesheet" type="text/css" href="dojo/dojox/grid/resources/tundraGrid.css" />

   <style type="text/css">
<!--
-->
   </style>
   </head>
      
   <body class="tundra" onResize="resizeWindow()">

<div class="all">
<?php /*      <form name="settings" style="position:fixed;top:430px;left:10px;"> */ ?>

	<!--
      <img src="image/pencil.png" alt="Pencil"    onclick="action('pencil')" style="position:fixed;top:10px;left:10px;"/> 
      <img src="image/brush.png"  alt="Brush"     onclick="action('brush')"  style="position:fixed;top:80px;left:10px;"/> 
      <img src="image/eraser.png" alt="Eraser"    onclick="action('eraser')" style="position:fixed;top:150px;left:10px;"/> 
      <img src="image/clear.png"  alt="Clear"     onclick="action('clear')"  style="position:fixed;top:220px;left:10px;"/> 
      <img src="image/drag.png"   alt="Drag Icon" onClick="action('drag')"   style="position:fixed;top:290px;left:10px;"/> 
      <img src="image/save.png"   alt="Save"      onclick="action('save')"   style="position:fixed;top:360px;left:10px;"/>
      -->
      
   <canvas id="canvasBg" width="<?php echo $editor->width;?>" height="<?php echo $editor->height;?>" style="border:1px solid #c3c3c3;position:fixed;top:<?php echo $editor->y;?>px;left:<?php echo $editor->x;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas>
      <canvas id="canvasDraw" width="<?php echo $editor->width;?>" height="<?php echo $editor->height;?>" style="border:1px solid #c3c3c3;position:fixed;top:<?php echo $editor->y;?>px;left:<?php echo $editor->x;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas>
      <canvas id="canvasIcon" width="<?php echo $editor->width;?>" height="<?php echo $editor->height;?>" style="border:1px solid #c3c3c3;position:fixed;top:<?php echo $editor->y;?>px;left:<?php echo $editor->x;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas>
      <canvas id="canvasTool" width="<?php echo $editor->width;?>" height="<?php echo $editor->height;?>" style="border:1px solid #c3c3c3;position:fixed;top:<?php echo $editor->y;?>px;left:<?php echo $editor->x;?>px;"> 
         Your browser  does not support the canvas element.
      </canvas>
      <canvas id="canvasSave" width="<?php echo $editor->width;?>" height="<?php echo $editor->height;?>" style="border:1px solid #c3c3c3;position:fixed;top:<?php echo $editor->y;?>px;left:<?php echo $editor->x;?>px;" oncontextmenu="canvasicon.drawMenu(); return false;" onclick="canvasicon.clearMenu();"> 
         Your browser  does not support the canvas element.
      </canvas>
      
      <form name="status" style="position:fixed;top:<?php echo $editor->height + $editor->y + 20;?>px;left:80px;">
      <textarea type="text" name="display"></textarea>
      </form>

      
      <!-- top bar -->
      <div class="topbar" id='topbar'>
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tr>
          <td width="89">
            <table width="212" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="89"><div class="menuItem" onmouseout="MM_showHideLayers('apDiv1','','hide')"><div class="topmenu_item" onmouseover="MM_showHideLayers('apDiv1','','show')">Programs</div>
                <div id="apDiv1" onmouseover="MM_showHideLayers('apDiv1','','show')">
                  <table width="150" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="#">Sample Application 1</a></div></td>
                    </tr>
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="#">Sample Application 2</a></div></td>
                    </tr>
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="#">Sample Application 3</a></div></td>
                    </tr>
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="#">Sample Application 4</a></div></td>
                    </tr>
                  </table>
                </div>
                </div></td>
                <td width="72"><div class="menuItem" onmouseout="MM_showHideLayers('apDiv2','','hide')"><div class="topmenu_item" onmouseover="MM_showHideLayers('apDiv2','','show')">System</div>
                <div id="apDiv2" onmouseover="MM_showHideLayers('apDiv2','','show')">
                  <table width="150" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="#">Profile</a></div></td>
                    </tr>
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="#">Change Password</a></div></td>
                    </tr>
                    <tr>
                      <td bgcolor="#CCCCCC"><div class="menuItem"><a href="logout.php">Log out</a></div></td>
                    </tr>
                  </table>
                </div>
                </div></td>
                <td width="93"></td>
              </tr>
            </table>
           </td>
           <td align="right">
           	<div id="topbarright">8:26 PM</div>
           </td>
          </tr>
        </table>
   </div>
      

	<!-- Account info -->
    <div dojoType="dijit.TitlePane" title="Account" style="width:90px;">
    	<div class="userinfo"><?php echo $username; ?></div>
        <form action="logout.php" style="margin-bottom:0"><button type="submit">Log out</button></form>
   </div>
    <br/>
    
<!-- The drawing tools -->
    <div dojoType="dijit.TitlePane" title="Drawing" style="width:90px;">
      <table width="63" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td width="63"><img src="image/pencil.png" alt="Pencil" onClick="action('pencil')" class="toolIcon"/></td>
        </tr>
        <tr>
          <td><img src="image/brush.png" alt="Brush" onClick="action('brush')" class="toolIcon" /></td>
        </tr>
        <tr>
          <td><img src="image/eraser.png" alt="Eraser" onClick="action('eraser')" class="toolIcon"/></td>
        </tr>
        <tr>
          <td><img src="image/clear.png" alt="Clear"  onClick="action('clear')" class="toolIcon" /></td>
        </tr>
        <tr>
          <td><img src="image/drag.png" alt="Drag Icon" onClick="action('drag')" class="toolIcon" /></td>
        </tr>
        <tr>
          <td><img src="image/save.png" alt="Save"  onClick="action('save')" class="toolIcon"/></td>
        </tr>
      </table>
	</div>

	<!-- Context menu that appears when users right click -->
	<div class="context_menu" id="context_menu">
	</div>
      
    <!-- Dialogs -->
	<!-- Login dialog box -->
    <div jsId="loginDlg" dojoType="dijit.Dialog" title="Login">
        <div id='loginStatus' class='loginStatus'></div>
            <table>
              <tr>
              <td><label for="username" title="User name">Username</label></td>
                  <td><input dojoType="dijit.form.TextBox" type="text" id="username" name="username" required="true" /></td>
              </tr>
              <tr>
                  <td><label for="password">Password: </label></td>
                  <td><input dojoType="dijit.form.TextBox" type="password" id="password" name="password" required="true" /></td>
              </tr>
              <tr>
                  <td colspan="2" align="center">
                      <button dojoType="dijit.form.Button" type="submit" jsId='loginBtn'>Login</button></td>
              </tr>
            </table>
    </div>
    
	<!-- Create New Folder dialog box -->
    <div jsId="createFolderDlg" dojoType="dijit.Dialog" title="Create New Folder">
        <div class='loginStatus'></div>
            <table>
              <tr>
              <td><label for="username" title="User name">Folder Name</label></td>
                  <td><input name="foldername" type="text" id="foldername" value="Document Name" dojoType="dijit.form.TextBox" required="true" /></td>
              </tr>
              <tr>
              <td colspan="2">Icon</td>
              </tr>
              <tr>
              <td colspan="2"><form name="folderIconForm" method="post" action="">
                <label><input name="folderIcon" type="radio" value="brown" checked><img src="image/folder_brown.png" width="64" height="64"></label>
                <label><input type="radio" name="folderIcon" value="orange"><img src="image/folder_orange.png" width="64" height="64"></label>
                <label><input type="radio" name="folderIcon" value="green"><img src="image/folder_green.png" width="64" height="64"></label>
                <label><input type="radio" name="folderIcon" value="white"><img src="image/folder_white.png" width="64" height="64"></label>
              </form></td>
              </tr>
              <tr>
                  <td colspan="2" align="center">
                      <button dojoType="dijit.form.Button" type="submit" jsId='createFolderBtn'> Create </button></td>
              </tr>
            </table>
    </div>
    
	<!-- Create Arrange Icons dialog box -->
    <div jsId="autoArrangeDlg" dojoType="dijit.Dialog" title="Arrange icons">
            <table>
              <tr>
              <td>&nbsp;</td>
              </tr>
              <tr>
              <td><form name="arrangeIconForm" method="post" action="">
                <label><input name="arrangeIcons" type="radio" value="vertical" checked><img src="image/vertical.jpg" width="65" height="65"></label>
                <label><input type="radio" name="arrangeIcons" value="horizontal"><img src="image/horizontal.jpg" width="65" height="65"></label>
                <label><input type="radio" name="arrangeIcons" value="circle"><img src="image/circle.jpg" width="65" height="65"></label>
              </form></td>
              </tr>
              <tr>
                  <td align="center">
                      <button dojoType="dijit.form.Button" type="submit" jsId='arangeIconsBtn'> Arrange</button></td>
              </tr>
            </table>
   </div>

	<!-- Create Change Desktop Background dialog box -->
    <div jsId="desktopBackgroundDlg" dojoType="dijit.Dialog" title="Desktop Background">
            <table>
              <tr>
              <td>&nbsp;</td>
              </tr>
              <tr>
              <td><form action="" method="post" enctype="multipart/form-data" name="backgroundForm">
                <label><input name="backgroundImage" type="radio" value="bg1.jpg" checked><img src="image/bg1.jpg" width="65" height="49"></label>
                <label><input type="radio" name="backgroundImage" value="bg2.jpg"><img src="image/bg2.jpg" width="65" height="49"></label>
                <label><input type="radio" name="backgroundImage" value="bg3.jpg"><img src="image/bg3.jpg" width="65" height="49"></label>
                <label>  <input type="radio" name="backgroundImage" value="bg4.jpg">
                  <img src="image/bg4.jpg" width="65" height="49"></label>
                <label>  <input type="radio" name="backgroundImage" value="bg5.jpg">
                  <img src="image/bg5.jpg" width="65" height="49"></label>
                  <br>
                  <br>
                  Upload your background
                  <br>
                  <input type="file" name="backgroundUpload" id="backgroundUpload">
                
              </form></td>
              </tr>
              <tr>
                  <td align="center">
                      <button dojoType="dijit.form.Button" type="submit" jsId='changeBackgroundBtn'> Change </button></td>
              </tr>
            </table>
  </div>


	<div id="colorPane" style="position:absolute;top:300px;left:200px;display:none">
    <div style="background:#999; display:block; text-align:right">
    <a href='javascript:closeColorPane()'>Close</a> &nbsp;&nbsp;
    </div>
      <table cellspacing="0" border="0">
      <tr>
<?php
         $colorArrayA = array("#F0F8FF","#000000","#000080","#00008B","#0000CD","#0000FF","#006400","#008000","#008080","#008B8B","#00BFFF","#00CED1","#00FA9A","#00FF00","#00FF7F","#00FFFF",
                              "#00FFFF","#191970","#1E90FF","#20B2AA","#228B22","#2E8B57","#2F4F4F","#32CD32","#3CB371","#40E0D0","#4169E1","#4682B4","#483D8B","#48D1CC","#4B0082","#556B2F");
         $colorArrayB = array("#5F9EA0","#6495ED","#66CDAA","#696969","#6A5ACD","#6B8E23","#708090","#778899","#7B68EE","#7CFC00","#7FFF00","#7FFFD4","#800000","#800080","#808000","#808080",
                              "#87CEEB","#87CEFA","#8A2BE2","#8B0000","#8B008B","#8B4513","#8FBC8F","#90EE90","#9370D8","#9400D3","#98FB98","#9932CC","#9ACD32","#A0522D","#A52A2A","#A9A9A9");
         $colorArrayC = array("#ADD8E6","#ADFF2F","#AFEEEE","#B0C4DE","#B0E0E6","#B22222","#B8860B","#BA55D3","#BC8F8F","#BDB76B","#C0C0C0","#C71585","#CD5C5C","#CD853F","#D2691E","#D2B48C",
                              "#D3D3D3","#D87093","#D8BFD8","#DA70D6","#DAA520","#DC143C","#DCDCDC","#DDA0DD","#DEB887","#E0FFFF","#E6E6FA","#E9967A","#EE82EE","#EEE8AA","#F08080","#F0E68C");
                              //"#FFEBCD","#FFEFD5","#FFF0F5","#FFF5EE","#FFF8DC","#FFFACD","#FFFAF0","#FFFAFA","#FFFF00","#FFFFE0","#FFFFF0","#FFFFFF");

         foreach($colorArrayA as $color)
            echo '         <td width="20" height="20" bgcolor="' . $color . '" onclick="cColor(this.bgColor)"></td>'."\n";
         echo '      </tr><tr>'."\n";
         foreach($colorArrayB as $color)
            echo '         <td width="20" height="20" bgcolor="' . $color . '" onclick="cColor(this.bgColor)"></td>'."\n";
         echo '      </tr><tr>'."\n";
         foreach($colorArrayC as $color)
            echo '         <td width="20" height="20" bgcolor="' . $color . '" onclick="cColor(this.bgColor)"></td>'."\n";
         echo '      </tr><tr>'."\n";
?> 
</tr></table>
</div>

	<!-- Folder Content -->	
    <div jsId="folderContentDlg" dojoType="dijit.Dialog" title="Folder" style="width:420px;height:240px">
        <div id="gridNode" style="width:400px;height:200px"></div>
    </div>
    
</div>
</body>
</html><?php }?>
